import type { App, Plugin } from 'vue'
import MD5Encrypt from 'js-md5'
import { useCache } from '@/hooks/web/useCache'
import { useAppStore } from '@/store/modules/app'
import { i18n } from '@/plugins/vueI18n'

import { useLocaleStoreWithOut } from '@/store/modules/locale'
const localeStore = useLocaleStoreWithOut()
const curLang = localeStore.getCurrentLocale.lang
const langType = curLang == 'zh_HK' ? 1 : curLang == 'zh_CN' ? 2 : 3
/***
 * @description: 获取当前用户
 * @author Elwin ZHANG
 * @date 2022/5/18 14:12
 */
export const getCurUser = (): any => {
  const { wsCache } = useCache()
  const appStore = useAppStore()
  const userData = wsCache.get(appStore.getUserInfo)
  if (userData) {
    return userData.data.user
  }
  return {}
}

/***
 * @description  获取后端返回的消息
 * @param msg 消息key，用于获取国际化消息
 * @param data 补充的数据，用于拼接在消息后面
 * @return 当前语言的消息字符串
 * @author Elwin ZHANG
 * @date 2022/8/1 14:19
 */
export const getBackEndMsg = (key: string, data: string): string => {
  let message = ''
  if (key) {
    if (key.indexOf('.') > 0) {
      const { t } = i18n.global
      message = t(key)
    } else {
      message = key
    }
  }
  if (data) {
    message += ' ' + data
  }
  return message
}

/***
 * @description: 获取Token
 * @author Elwin ZHANG
 * @date 2022/5/18 14:08
 */
export const getToken = (): string => {
  const { wsCache } = useCache()
  const appStore = useAppStore()
  const userData = wsCache.get(appStore.getUserInfo)
  if (userData) {
    return userData.data.token
  }
  return ''
}
/**
 * @description: 获取加密后的密码
 * @param password 明文
 * @return  加密后密码
 * @author Elwin ZHANG
 * @date 2022/5/18 11:54
 */
export const getMd5Password = (password: string): string => {
  const pw = password + `$1#.@Ez`
  return MD5Encrypt(pw)
}

/**
 * @description: 返回相应的数据字典
 * @param datalist 所有的数据
 * @param key 需要查的数据key
 * @return  返回这个key的数据
 * @author lxc
 * @date
 */
//  InterestCalculate	计息方法	計息方法
//  Identity		證件類別	证件類别
//  Resident	住宅類別	住宅類别
//  Source		來源		来源
//  LoanType	貸款類型	貸款類型
//  LoanPurpose	貸款用途	貸款用途
//  DocType	文件類別	文件類别
//  FollowType	跟進事項	跟进事项
//  LoanPayment	放款方式	放款方式
//  Repayment	還款方式	还款方式

export const getDicData = (datalist, key) => {
  for (const item of datalist) {
    if (item.dicKey == key) return item.dicValueList
  }
}

/**
 *
 * @param component 需要註册的组件
 * @param alias 组件别名
 * @returns any
 */

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any
  comp.install = (app: App) => {
    app.component(comp.name || comp.displayName, component)
    if (alias) {
      app.config.globalProperties[alias] = component
    }
  }
  return component as T & Plugin
}

/**
 * @param str 需要转下划线的驼峰字符串
 * @returns 字符串下划线
 */
export const humpToUnderline = (str: string): string => {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}

/**
 * @param str 需要转驼峰的下划线字符串
 * @returns 字符串驼峰
 */
export const underlineToHump = (str: string): string => {
  return str.replace(/\-(\w)/g, (_, letter: string) => {
    return letter.toUpperCase()
  })
}

export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
  dom.style.setProperty(prop, val)
}

/**
 * 查找数组对象的某个下标
 * @param {Array} ary 查找的数组
 * @param {Functon} fn 判断的方法
 */
// eslint-disable-next-line
export const findIndex = <T = Recordable>(ary: Array<T>, fn: Fn): number => {
  if (ary.findIndex) {
    return ary.findIndex(fn)
  }
  let index = -1
  ary.some((item: T, i: number, ary: Array<T>) => {
    const ret: T = fn(item, i, ary)
    if (ret) {
      index = i
      return ret
    }
  })
  return index
}

export const trim = (str: string) => {
  return str.replace(/(^\s*)|(\s*$)/g, '')
}

/**
 * @param {Date | number | string} time 需要转换的时间
 * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
 */
export function formatTime(time: Date | number | string, fmt: string) {
  if (!time) return ''
  else {
    time = time.toString()
    if (time.includes('-')) time = time.replace(/\-/g, '/')
    const date = new Date(time)
    // console.log(date)
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds()
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
        )
      }
    }

    return fmt
  }
}

//时间计算(年龄、入职时间计算)
/**
 *@author lxc
 *@description:时间计算(年龄、入职时间计算)，距离当前多少年
 *@param:传入时间距离
 *@date: 2022-07-27 10:10:56
 **/
export function timeCalculation(time: string) {
  if (time) {
    const timeVal = formatTime(time, 'yyyy-MM-dd')
    const birArr = timeVal.split('-')
    const birYear = birArr[0]
    const birMonth = birArr[1]
    const birDay = birArr[2]
    // eslint-disable-next-line no-var
    const gd = new Date()

    const nowYear = gd.getFullYear()
    const nowMonth = gd.getMonth() + 1 //记得加1
    const nowDay = gd.getDate()
    let returnAge
    if (birArr == null) {
      return false
    }
    // eslint-disable-next-line no-var
    const d = new Date(birYear, birMonth - 1, birDay)
    if (d.getFullYear() == birYear && d.getMonth() + 1 == birMonth && d.getDate() == birDay) {
      if (nowYear == birYear) {
        returnAge = 0 //
      } else {
        const ageDiff = nowYear - birYear //
        if (ageDiff > 0) {
          if (nowMonth == birMonth) {
            const dayDiff = nowDay - birDay //
            if (dayDiff < 0) {
              returnAge = ageDiff - 1
            } else {
              returnAge = ageDiff
            }
          } else {
            const monthDiff = nowMonth - birMonth //
            if (monthDiff < 0) {
              returnAge = ageDiff - 1
            } else {
              returnAge = ageDiff
            }
          }
        } else {
          // return '出生日期晚于今天，数据有误' //返回-1 表示出生日期输入错误 晚于今天
        }
      }
      //state.age = returnAge <= 0 ? 0 : returnAge
      return returnAge <= 0 ? 0 : returnAge
    } else {
    }
  } else {
    return ''
  }
}
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * For search
 * @param {Array} data
 * @param {string} fil
 * @param {Array} keyList
 */
export function filterArr(data, fil, keyList) {
  if (fil.trim() === '') {
    return data
  }
  const outArr = []
  data.forEach((dataItem) => {
    let filterStr = ''
    keyList.forEach((item) => {
      if (dataItem.hasOwnProperty(item)) {
        filterStr = filterStr + dataItem[item]
      }
    })
    if (filterStr.includes(fil)) {
      outArr.push(dataItem)
    }
  })
  return outArr
}

/**
 * 生成随机字符串
 */
export function toAnyString() {
  const str: string = 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'.replace(/[xy]/g, (c: string) => {
    const r: number = (Math.random() * 16) | 0
    const v: number = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString()
  })
  return str
}
/**
 *@author lxc
 *@description: 计算首期时间，尾期时间，这个每个月还款的
 *@param:,起息时间，还款总期,期数减几
 *@date: 2022-06-15 16:44:17
 **/

export function interestCalculationTime(loanDate, totalPeriod, reduce) {
  const iTime = loanDate.split('-')
  const year = Number(iTime[0]) //iTime[0]
  const moon = Number(iTime[1])
  const day = Number(iTime[2])
  //首期
  //let fyear = year,
  // fmoon = moon + 1
  //尾期
  let eyear = year,
    emoon = moon + Number(totalPeriod - reduce)
  // if (fmoon > 12) {
  //fyear = year + 1
  //  fmoon = 1
  // }
  eyear += Math.floor(emoon / 12)
  emoon = emoon % 12
  if (emoon == 0) {
    emoon = 12
    eyear -= 1
  }
  const ld = eyear.toString() + '-' + emoon.toString() + '-' + day
  return [getNextMonth(loanDate), getNextMonth(ld)] //首期时间，尾期时间
}
//获取下个月时间
export function getNextMonth(date) {
  const arr = date.split('-')
  const year = arr[0] //获取当前日期的年份
  const month = arr[1] //获取当前日期的月份
  const day = arr[2] //获取当前日期的日
  // let days = new Date(year, month, 0)
  // days = days.getDate() //获取当前日期中的月的天数
  // console.log(days)
  let year2 = year
  let month2 = parseInt(month) + 1
  if (month2 == 13) {
    year2 = parseInt(year2) + 1
    month2 = 1
  }
  let day2 = day
  let days2 = new Date(year2, month2, 0)
  console.log(days2)
  days2 = days2.getDate()
  if (day2 > days2) {
    day2 = days2
  }
  if (month2 < 10) {
    month2 = '0' + month2
  }

  const t2 = year2 + '-' + month2 + '-' + day2

  return t2
}
/**
 *@author lxc
 *@description:计算7天，14天的首期和尾期日期
 *@param:计息时间，总的周期，7/14天
 *@date: 2022-08-31 11:06:33
 **/
export function interestCalculationTime2(loanDate, totalPeriod, dataTime) {
  const t = dataTime * totalPeriod
  return [getNextMonth2(dataTime, loanDate), getNextMonth2(t, loanDate)] //首期时间，尾期时间
}
export function getNextMonth2(n, loanDate) {
  const currentDate = formatTime(loanDate, 'yyyy-MM-dd') //new Date()
  const now = Date.parse(currentDate)
  const preDate = new Date(now + n * 24 * 3600 * 1000)
  return formatTime(preDate, 'yyyy-MM-dd')
}
/**
 *@author lxc
 *@description:获取当前时间，返回时间格式为：yyyy-MM-dd
 *@param:
 *@date: 2022-06-23 17:20:14
 **/
export function getCurrentTime() {
  const nowDate = new Date()
  return formatTime(nowDate, 'yyyy-MM-dd')
}

/**
 * 獲取某一年某月的最後一天
 * @param:year:年份yyyy month: 月份MM
 */
export function getLastDay(year, month) {
  let new_year = year
  let new_month = month++
  if (month > 12) {
    new_month -= 12
    new_year++
  }
  const new_date = new Date(new_year, new_month, 1)
  return new Date(new_date.getTime() - 1000 * 60 * 60 * 24).getDate()
}

/**
 *@author lxc
 *@description:按照语言获取贷款类型
 *@param:
 *@date: 2022-11-08 16:38:55
 **/
export function getLoanTypeText(dic) {
  {
    if (langType == 2) {
      return dic.showCn
    } else if (langType == 1) return dic.showText
    else return dic.showEn
  }

  return ''
}
/**
 *@author lxc
 *@description:当用户输入的证件编号为8或者9位的时候，当用户输入完离开输入框时，自动讲最后一个数字或字母添加上( )，用英文输入法的( )
 *@param:证件号码
 *@date: 2022-11-22 11:59:52
 **/
export function dealWithPassPortNo(passPortNoStr) {
  const p = passPortNoStr.substring(passPortNoStr.length - 1, passPortNoStr.length)
  const str = passPortNoStr.substring(0, passPortNoStr.length - 1)
  return str + '(' + p + ')'
}
